package com.sann.demo.service.impl;

import com.sann.demo.dao.IAccountDao;
import com.sann.demo.domain.Account;
import com.sann.demo.service.IAccountService;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;
import org.springframework.transaction.annotation.Propagation;
import org.springframework.transaction.annotation.Transactional;

@Service("accountService")
@Transactional(propagation = Propagation.SUPPORTS, readOnly = true)
public class AccountServiceImpl implements IAccountService {

    @Autowired
    private IAccountDao accountDao;

    @Override
    public Account findAccountById(Integer accountId) {
        return accountDao.findAccountById(accountId);
    }

    @Transactional(propagation = Propagation.REQUIRED, readOnly = false)
    @Override
    public void transfer(String sourceName, String targetName, float money) {
        // 查询转出账户
        Account source = accountDao.findAccountByName(sourceName);

        // 查询转入账户
        Account target = accountDao.findAccountByName(targetName);

        // 转出账户减钱
        source.setMoney(source.getMoney() - money);

        // 转入账户加钱
        target.setMoney(target.getMoney() + money);

        // 更新转出账户
        accountDao.updateAccount(source);

        // 模拟异常
        int i = 1/0;

        // 更新转入账户
        accountDao.updateAccount(target);
    }
}
